package com.goparry.taskman.aws;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.Owner;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.goparry.taskman.R;
import com.goparry.taskman.repository.TaskNote;

public class AWSUtils {
	private static AmazonS3 s3 = null;
	private static String BUCKET = "TaskManager";
	private static String PREFIX = "task-notes/";
	private static Context mContext;
	private static BasicAWSCredentials mCredentials;
	static {
		System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
		try {
			XMLReader reader = XMLReaderFactory.createXMLReader();
		}
		catch ( SAXException e ) {
			Log.e( "SAXException", e.getMessage() );
		}
	}
	public static void saveTaskNote(String taskName, TaskNote taskNote, File file) {
		// Get the number of objects with this prefix
		// The saved file name will be <taskName><nObjects+1>.<format>
		ObjectListing objects = getInstance().listObjects(BUCKET, PREFIX + taskName);
		int nObjects = objects.getObjectSummaries().size() + 1;
		String key = PREFIX + taskName + "/" + Integer.toString(nObjects);
		PutObjectRequest request = new PutObjectRequest(BUCKET, key, file);
		ObjectMetadata metadata = new ObjectMetadata();
		metadata.addUserMetadata("name", taskNote.getName());
		metadata.addUserMetadata("author", taskNote.getAuthor());
		metadata.addUserMetadata("type", taskNote.getType());
		request.setMetadata(metadata);
		
		getInstance().putObject(request);
		// Delete the file from the local device
		file.delete();
		
	}
	public static List<TaskNote> getTaskNotes(String taskName) {
		List<TaskNote> taskNotes = new ArrayList<TaskNote>();
		ListObjectsRequest lor = new ListObjectsRequest();
		lor.setBucketName(BUCKET);
		lor.setPrefix(PREFIX + taskName + "/");
		lor.setDelimiter("/");
		ObjectListing objects = getInstance().listObjects(lor);
		List<S3ObjectSummary> objectSummaries = objects.getObjectSummaries();
		S3Object obj;
		for (S3ObjectSummary objL : objectSummaries) {
			obj = getInstance().getObject(new GetObjectRequest(BUCKET, objL.getKey()));
			ObjectMetadata metadata = obj.getObjectMetadata();
			Map<String, String> map = metadata.getUserMetadata();
			taskNotes.add(new TaskNote(map.get("name"), map.get("author"), map.get("type"), objL.getLastModified(), objL.getKey(), objL.getSize()));
		}
		
		return taskNotes;
	}
	public static InputStream getTaskNoteFile(String key, String extension) {
		S3Object obj = getInstance().getObject(BUCKET, key);
        InputStream inputStream = obj.getObjectContent();
		return inputStream;
	}
	public static void initialize(Context context){
		mContext = context;
		Resources resources = context.getResources();
		mCredentials = new BasicAWSCredentials(resources.getString(R.string.AmazonAccessKey), resources.getString(R.string.AmazonSecretKey));
	}
	public static AmazonS3 getInstance() {
        if ( s3 == null ) {
		    s3 = new AmazonS3Client( mCredentials );
        }
        return s3;
	}
    public static File createTextFile(String text) throws IOException {
       	String path = mContext.getFilesDir().getAbsolutePath();
        File file = new File(path, "tmp.txt");
        if (!file.exists()) file.createNewFile();
        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write(text);
        writer.close();

        return file;
    }


}
